package com.xiaoxu.privatechat.service.common;

import com.xiaoxu.privatechat.bean.PageBean;
import com.xiaoxu.privatechat.dao.common.MsgContentDao;
import com.xiaoxu.privatechat.entity.common.MsgContent;
import org.springframework.data.domain.*;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xiaoxu
 * @description 消息内容管理service
 * @date 2023/2/13
 */
@Service
public class MsgContentService {

    @Resource
    private MsgContentDao msgContentDao;

    /**
     * @param id 内容信息id
     * @return MsgContent
     * @description 根据id查询
     */
    public MsgContent find(Long id) {
        return msgContentDao.find(id);
    }


    /**
     * @param msgContent 内容信息
     * @return MsgContent
     * @description 添加/编辑操作
     */
    public MsgContent save(MsgContent msgContent) {
        return msgContentDao.save(msgContent);
    }

    /**
     * @return long
     * @description 返回总数
     */
    public long total() {
        return msgContentDao.count();
    }

    /**
     * @param msgContent 内容信息
     * @param pageBean   分页
     * @return PageBean<MsgContent>
     * @description 获取消息列表
     */
    public PageBean<MsgContent> findList(MsgContent msgContent, PageBean<MsgContent> pageBean) {
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("msg", GenericPropertyMatchers.contains());
        withMatcher = withMatcher.withIgnorePaths("attachSize");
        Example<MsgContent> example = Example.of(msgContent, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize(), Sort.by(Direction.DESC, "createTime"));
        Page<MsgContent> findAll = msgContentDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }
}
